﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace InterfaceFiles
{
  public class PDXSWMM4InterfaceReader : IInterfaceReader
  {
    private FileStream fileStream;
    private BinaryReader reader;
    private int recordSize;
    private int positionInRecord;

    public PDXSWMM4InterfaceReader(string fileName)
    {
      fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read,
        FileShare.Read);
      reader = new BinaryReader(fileStream);
      getRecordSize();
    }

    private bool endOfRecord
    {
      get
      {
        return positionInRecord == recordSize;
      }
    }

    private bool startOfRecord
    {
      get
      {
        return positionInRecord == 0;
      }
    }

    private void checkRecordSize()
    {
      if (endOfRecord)
      {
        getRecordSize();
        if (!IsEndOfFile)
          getRecordSize();
        else
          recordSize = 0;
        positionInRecord = 0;
      }
    }

    private void getRecordSize()
    {
      int buffer = reader.ReadInt32();
      recordSize = buffer;
    }

    private void rewindRecordSize()
    {
      fileStream.Position -= sizeof(int);
    }

    public string FileName
    {
      get;
      set;
    }

    public int ReadInt()
    {
      int buffer = reader.ReadInt32();
      positionInRecord += sizeof(int);
      checkRecordSize();
      return buffer;
    }

    public string ReadString(int length)
    {
      char[] buffer = new char[length];
      buffer = reader.ReadChars(length);
      positionInRecord += length;
      checkRecordSize();
      return new string(buffer);
    }

    public double ReadDouble()
    {
      Single buffer = reader.ReadSingle();
      positionInRecord += sizeof(Single);
      checkRecordSize();
      return (double)buffer;
    }

    public bool IsEndOfFile
    {
      get
      {
        return reader.PeekChar() == -1;
      }
    }

    public void Close()
    {
      reader.Close();
    }
  }
}
